<template>
  <div class="w-color-picker-right-bar">
    <div id="w-alphaBar" :style="{ 'background': bg }" @click="handleClick" class="slider-bar">
      <div id="w-alphaPoint" :style="{ left: sliderLeft + 'px' }" class="slider-bar-pointer bg-alpha"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'w-slider-alpha',
  props: {
    color: {
      required: true
    },
  },
  data() {
    return {
      isDragging: false,
      sliderLeft: 0,
      // bg: ''
    }
  },
  computed: {
    alphaValue() {
      const alpha = this.color.get('alpha');
      return alpha;
    },
    bg(){
      return `linear-gradient(to right, rgba(255, 69, 0, 0) 0%,${this.color.colorValue} 100%)`
    }
  },
  watch: {
    alphaValue(val) {
      this.updateView();
    }
  },

  mounted() {
    let that = this;
    let rightBar = document.querySelector('#w-alphaBar');
    this.updateView();
    rightBar.addEventListener('mousedown', e => {
      if (that.isDragging) return; //防止重复
      document.onselectstart = () => false;
      document.ondragstart = () => false;
      document.addEventListener('mousemove', that.moveFn);
      document.addEventListener('mouseup', that.upFn);
      that.isDragging = true;
    })
  },
  methods: {
    //点击时
    handleClick(event) {
      const thumb = document.querySelector('#w-alphaPoint');
      const target = event.target;
      if (target !== thumb) {
        this.moveFn(event);
      }
    },

    moveFn(event) {
      //滑轨位置信息
      let sliderBar = document.querySelector('#w-alphaBar').getBoundingClientRect();
      let slider = document.querySelector('#w-alphaPoint');

      //滑块滑动的范围
      let left = event.clientX - sliderBar.left;
      left = Math.min(left, sliderBar.width - slider.offsetWidth / 2);
      left = Math.max(slider.offsetWidth / 2, left);//
      //将滑块滑动的范围转换成透明度
      let alphaValue = Math.round((left - slider.offsetWidth / 2) / (sliderBar.width - slider.offsetWidth) * 100);
      //记录色相
      this.color.set('alpha', alphaValue);

    },
    upFn(event) {
      console.log('松开')
      document.removeEventListener('mousemove', this.moveFn);
      document.removeEventListener('mouseup', this.upFn);
      document.onselectstart = null;
      document.ondragstart = null;
      this.isDragging = false;
    },
    //根据色想变化更新位置
    updateView() {
      let sliderBar = document.querySelector('#w-alphaBar').getBoundingClientRect();
      let slider = document.querySelector('#w-alphaPoint');
      const alphaValue = this.color.get('alpha');
      this.sliderLeft = Math.round((alphaValue / 100) * (sliderBar.width - slider.offsetWidth));
      // this.bg = `linear-gradient(to right, rgba(255, 69, 0, 0) 0%,${this.color.colorValue} 100%)`;
    }
  },
}
</script>

<style scoped>
@import './commom.css';

.w-color-picker-right-bar {
  background: url();
}
.bg-alpha{
  background: #ffffff;
}
</style>
